package com.haolijun.eecms.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.haolijun.eecms.common.R;
import com.haolijun.eecms.dao.TbUserDao;
import com.haolijun.eecms.entity.TbUser;
import com.haolijun.eecms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import static com.haolijun.eecms.common.TransitionUtils.arrayConversion;

/**
 * @ClassName UserServiceImpl
 * @Description TODO
 * @Author hljstart
 * @Date 2023/3/7 21:27
 * @Version 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private TbUserDao userDao;


    @Override
    public Set<String> searchUserRole(Integer userId) {
        Set<String> roles = userDao.searchUserRole(userId);
        return roles;
    }

    @Override
    public Integer login(HashMap map) {
        Integer userId = userDao.login(map);
        return userId;
    }

    @Override
    public HashMap searchUserSummary(Integer userId) {
        HashMap userMap = userDao.searchUserSummary(userId);
        return userMap;
    }

    @Override
    public R searchUserByPage(HashMap param) {
        // 1、 获取当前页数
        int page = (int) param.get("page");
        // 2、获取每一页的记录数
        int length = (int) param.get("length");
        // 3、计算出当前的要开始的页数
        int start = (page - 1) * length;
        // 4、放入到集合中
        param.put("start", start);
        // 5、获取总记录数
        long count = userDao.searchUserCount(param);
        // 6、获取用户信息
        List<HashMap> users = userDao.searchUserByPage(param);
        // 7、封装数据
        R r = R.ok().data("totalCount", count).data("pageSize", length).data("pageIndex", start).data("users", users);
        // 8、返回
        return r;
    }

    @Override
    public HashMap searUserById(Integer userId) {
        HashMap user = userDao.searUserById(userId);
        String rolesStr = (String) user.get("roles");
        List<String> roles = arrayConversion(rolesStr);
        user.put("roles", roles);
        return user;
    }

    @Override
    public int update(TbUser user) {
        user.setStatus((byte) 1);
        return userDao.update(user);
    }

    @Override
    public int insert(TbUser user) {
        user.setCreateTime(new Date());
        user.setStatus((byte) 1);
        return userDao.insert(user);
    }

    @Override
    public R deleteUserById(Integer userId) {
        int rows = userDao.deleteUserById(userId);
        if(rows > 0){
            StpUtil.logoutByLoginId(userId);
            return R.ok();
        }
        return R.error();
    }
}
